import { createDirs, homePath, saveText, uuid } from "@/utils";
import { DEFAULT_EMPTY_WORKFLOW_DATA, WorkflowType } from "../workflow";
import { create } from "@tauri-apps/plugin-fs";
import { dsInsert } from "../datasource";
import { SCHEDULER_TASK_TEMPLATE_CLASS_IDENTIFIER, WORKFLOW_CLASS_IDENTIFIER } from "@/services/constants";


export interface TaskTemplate {
    id?: number;
    identifier: string;
    name: string;
    title: string;
    icon?: string;
    task_type: string;
    content_type: SchedulerTaskContentType;
    content: string;
    cron: string;
    variable_schema_identifier: string;
    result_schema_identifier: string;
    comment?: string;
    options?: string;
    description?: string;
    workflow?: {
        path: string
    }[]
}

export enum SchedulerTaskType {
    WORKFLOW = "workflow",
}


export enum SchedulerTaskContentType {
    WORKFLOW = "workflow",
}

export const SCHEDULER_TASK_TYPE_SELECT_OPTIONS = [
    { value: 'workflow', label: '数据流' },
];


export const schedulerCreateEmptyTaskTemplate = async (value: { name: string; icon?: string; task_type: SchedulerTaskType }): Promise<any> => {
    const { name, icon, task_type } = value;
    let identifier = uuid();
    let taskContentType = SchedulerTaskContentType.WORKFLOW;
    let content = '';
    //
    if (task_type === SchedulerTaskType.WORKFLOW) {
        //新建一个workflow，并返回identifier
        let workflowIdentifier = uuid();
        try {
            //创建文件
            let home = await homePath();
            let exportPath = `${home}/flows/${workflowIdentifier}/`;
            await createDirs(exportPath);
            let filename = `${exportPath}/workflow.json`;
            await create(filename);
            await saveText(filename, JSON.stringify(DEFAULT_EMPTY_WORKFLOW_DATA));
            //插入workflow
            let wres = await dsInsert(0, WORKFLOW_CLASS_IDENTIFIER, {
                identifier: workflowIdentifier,
                name: name,
                icon: icon,
                title: name,
                workflow_type: WorkflowType.DataFlow,
                content_type: 'file',
                content: filename
            });
        } catch (err) {
            console.error(err);
        }
        content = workflowIdentifier;
        //
    }
    //插入taskTemplate
    try {
        let wres = await dsInsert(0, SCHEDULER_TASK_TEMPLATE_CLASS_IDENTIFIER, {
            identifier: identifier,
            name: name,
            icon: icon,
            title: name,
            task_type: task_type,
            content_type: taskContentType,
            content: content
        });
    } catch (err) {
        console.error(err);
    }
    return
}
